<?php

namespace App\Http\Controllers\Admin\Category;

use App\Models\Category\Category;
use App\Services\CategoryService;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\HttpException;

class ArticleCategoryController extends BaseController
{

    public $type = 'article';


        /**
         * 状态修改
         */
        public function status($id,Request $request)
        {
            $this->validateData($request);

            $category = Category::query()->where('id',$id)->first();

            if (empty($category)) {
                return $this->response->errorNotFound();
            }

            $category->update([
                'status' => $request->input('status')
            ]);

            return $this->response->noContent();
        }

    /**
     * 参数验证规则
     *
     * @param Request $request
     * @return array
     */
    public function rules(Request $request): array
    {
        $categoryService = new CategoryService(request(), $this->type);

        switch ($request->method()) {
            case 'GET':
                return [];
                break;
            case 'POST':
                return [
                    //bail在首次验证失败后立即终止验证。
                    'name' => ['bail', 'nullable', 'string', 'max:32'],
                    'nickname' => ['bail', 'required', 'string', 'max:50', function ($attr, $value, $fail) use ($categoryService) {

                        //属性的名称、属性的值以及$fail验证失败时应调用的回调
                        $result = $categoryService->checkCategoryNickname(request()->input('pid', null), $value);

                        if (!$result) {
                            return $fail('昵称重复');
                        }
                    }],
                    'pid' => 'nullable|integer'
                ];
                break;
            case 'PATCH':
                //从服务器中拿到id
                $id = route_parameter($this->type.'_category');

                if (empty($id)){
                    $id = route_parameter('id');
                }

                $category = $categoryService->getCacheCategory($id);

                if (empty($category)) {
                    throw new HttpException(404,'ID或路由错误');
                }

                return [
                    'name' => ['bail', 'nullable', 'string', 'max:32'],
                    'nickname' => ['bail', 'required', 'string', 'max:50', function ($attr, $value, $fail) use ($categoryService,$id) {
                        $result = $categoryService->checkCategoryNickname(request()->input('pid', null), $value, $id);
                        if (!$result) {
                            return $fail('昵称重复');
                        }
                    }],
                    'pid' => 'nullable|integer'
                ];
                break;
            case 'PUT':
                return [
                    'status' => 'bail|required'
                ];
                break;
        }
        return [];
    }

}
